package com.google.precinct.client.finder;

import com.google.gwt.core.client.GWT;
import com.google.gwt.maps.client.MapType;
import com.google.gwt.maps.client.MapUIOptions;
import com.google.gwt.maps.client.MapWidget;
import com.google.gwt.maps.client.geom.LatLng;
import com.google.gwt.maps.client.geom.Size;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.precinct.client.BreadCrumbManager;
import com.google.precinct.client.MainShell;
import com.google.precinct.common.PrecinctInfo;

public class FindRootPage extends Composite {

	private static FindPrecinctRootPageUiBinder uiBinder = GWT
			.create(FindPrecinctRootPageUiBinder.class);

	interface FindPrecinctRootPageUiBinder extends
			UiBinder<Widget, FindRootPage> {
	}

	@UiField
	SimplePanel leftSide;

	@UiField
	FlowPanel bottomLeftSide;

	@UiField
	MapWidget maps;

	private final MainShell ctr;

	private final BreadCrumbManager breadCrumb;
	private final PrecinctInfo precinctInfo;

	public FindRootPage(MainShell ctr, PrecinctInfo precinctInfo, BreadCrumbManager breadCrumb) {
		this.ctr = ctr;
		this.precinctInfo = precinctInfo;
		this.breadCrumb = breadCrumb;
		initWidget(uiBinder.createAndBindUi(this));

		initializeBreadCrumbs(precinctInfo.getPrecinctNo());
		initializeMaps();

		// Show City Selection Panel
		swapLeftPanel(new PrecinctSearchLPanel(this, precinctInfo, maps));
	}

	private void initializeMaps() {
		MapUIOptions options = MapUIOptions.newInstance(Size.newInstance(450, 300));
		options.setScaleControl(true);
		maps.setUI(options);
		for(MapType type : MapType.getDefaultMapTypes()) {
			maps.removeMapType(type);
		}
		maps.removeMapType(MapType.getPhysicalMap());
		maps.addMapType(MapType.getMapmakerNormalMap());
		maps.addMapType(MapType.getMapmakerHybridMap());

		maps.setCenter(LatLng.newInstance(11.781, 122.695), 5, MapType.getMapmakerHybridMap());
	}

	private void initializeBreadCrumbs(String precinctNo) {
		breadCrumb.pushEntry("Find Precinct " + precinctNo,
				new Runnable() {
			@Override
			public void run() {
				swapLeftPanel(new PrecinctSearchLPanel(FindRootPage.this, precinctInfo, maps));
			}
		},
				new Runnable() {
			@Override
			public void run() {
			}
		});
	}

	private void swapLeftPanel(Widget page) {
		if (leftSide.getWidget() != null) {
			leftSide.remove(leftSide.getWidget());
		}
		leftSide.add(page);
	}

}
